<?php
/**
 * 验证码生成
 * 可在执行的时候传入配置参数
 * 例子： $configArr = ['num' => 2,'width' => 150,'height' => 40,'size' => 12];
 *       $obj = Captcha::instance($configArr)->imgCode();
 *       Session::set('code', $obj->str);
 *       header('content-type:text/png;');
 *       echo $obj->img;
 */

namespace yphp;

class Captcha extends Instance
{
    # 默认配置
    private static $config = ['num'=>4,'width'=>250,'height'=>62,'size'=>24];

    // 构造函数
    function construct($configArr = [])
    {
        if(!empty($configArr) && is_array($configArr)){
            self::$config['num'] = is_int($configArr['num']) ? $configArr['num'] : self::$config['num'];
            self::$config['width'] = is_int($configArr['width']) ? $configArr['width'] : self::$config['width'];
            self::$config['height'] = is_int($configArr['height']) ? $configArr['height'] : self::$config['height'];
            self::$config['size'] = is_int($configArr['size']) ? $configArr['size'] : self::$config['size'];
        }
    }

    // 返回二维码对象
    static function imgCode()
    {
        $num    = self::$config['num'];
        $width  = self::$config['width'];
        $height = self::$config['height'];
        $size   = self::$config['size'];

        // 生成背景
        $im = imagecreatetruecolor($width, $height);
        imagefilledrectangle($im, 0, $height, $width, 0, imagecolorallocate($im, 243, 251, 254));
        // 字符组
        $charset = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
        $len = strlen($charset) - 1;
        // 干扰字符
        for ($i = 0; $i < 10; $i++) {
            $color = imagecolorallocate($im, mt_rand(150, 225), mt_rand(150, 225), mt_rand(150, 225));
            for ($j = 0; $j < 5; $j++) imagestring($im, 5, mt_rand(-10, $width), mt_rand(-10, $height), $charset[mt_rand(0, $len)], $color);
        }
        // 主色调：曲线、字体
        $color = imagecolorallocate($im, mt_rand(1, 150), mt_rand(1, 150), mt_rand(1, 150));
        // 绘制曲线：振幅、角度偏移、Y轴偏移
        $A = mt_rand($height / 4, $height / 2);
        $S = mt_rand(-$height / 4, $height / 4);
        $H = mt_rand(-$height / 4, $height / 4);
        $w = (2 * M_PI) / mt_rand($width / 4, $width * 2);
        for ($d = 0; $d <= $width; $d++) {
            $y = $A * sin($w * $d + $S) + $H + $height / 2;
            $i = $size / 5;
            while (--$i > 0) {
                imagesetpixel($im, $d + $i, $y + $i, $color);
            }
        }
        // 验证码
        $str = '';
        $dw = $width / ($num + 1) / 2;
        for ($i = 1; $i <= $num; $i++) {
            $code = $charset[mt_rand(0, $len)];
            imagettftext($im, $size, mt_rand(-40, 40), mt_rand($dw * (2 * $i - 1), $dw * 2 * $i), $height / 1.4, $color, YP . 'font.ttf', $code);
            $str .= $code;
        }
        // 保存为对象
        $obj = new \StdClass();
        $obj->str = $str;
        ob_start();
        imagepng($im);
        $obj->img = ob_get_clean();
        imagedestroy($im);
        return $obj;
    }

}